//
//  NewsListController.swift
//  MyTouTiao
//
//  Created by Yuri on 2018/3/16.
//  Copyright © 2018年 Yuri. All rights reserved.
//

//新闻列表页

import UIKit

class NewsListController: UITableViewController {
    
    var dataList : [HttpPost] = []
    //分类ID
    var categoryId : Int!
    //保持一个Navigation的引用
    var parentNavigation : UINavigationController?

    override func viewDidLoad() {
        super.viewDidLoad()

        //下拉刷新（TableView自带的）
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: #selector(getData), for: .valueChanged)
        refreshControl?.beginRefreshing()
        
        getData()
        
        //本地通知
        NotificationCenter.default.addObserver(self, selector: #selector(getData), name: NotificationHelper.updateList, object: nil)
        
    }
    
    @objc func getData() {
        NewsListHttpModel.getCategoryPost(id: categoryId) { (newsListModel) in
            
            if let model = newsListModel {
                //更新列表
                //要放在主线程中
                OperationQueue.main.addOperation {
                    self.dataList = model.posts!
                    self.tableView.reloadData()
                    
                    self.refreshControl?.endRefreshing()
                }
            } else {
                print("网络请求错误")
                
                self.refreshControl?.endRefreshing()
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dataList.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let item = dataList[indexPath.row]
        
        if let thumbnail = item.thumbnail {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) as! NewsItemImageCell
            cell.titleLabel.text = item.title
            cell.commentLabel.text = "评论\(item.commentCount ?? 0)条"
            cell.iconView.dlm_setImage(url: thumbnail, placeHolderImageType: .currency)
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell", for: indexPath) as! NewsItemTextCell
            cell.titleLabel.text = item.title
            cell.commentLabel.text = "评论\(item.commentCount ?? 0)条"
            
            return cell
        }
    }
    
    ///用户点击了某个Item
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = dataList[indexPath.row]
        
        let detailVC = storyboard?.instantiateViewController(withIdentifier: "SBID_NEWS_DETAIL") as! NewsDetailController
        
        detailVC.post = item
        
        //模态弹出
//        present(detailVC, animated: true, completion: nil)
        
        parentNavigation?.pushViewController(detailVC, animated: true)
        
        //选中之后 取消选择状态
        tableView.deselectRow(at: indexPath, animated: true);
        
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
